import callback from '../function/callback'
import map from './map'
import pluck from '../object/pluck'

function sortedBy(obj, iteratee, context) {
  let index = 0
  iteratee = callback(iteratee, context)

  const res = map(obj, function (value, key, list) {
    return {
      value: value,
      index: index++,
      criteria: iteratee(value, key, list)
    }
  }).sort((left, right) => {
    const a = left.criteria
    const b = right.criteria
    if (a !== b) {
      return a - b
    }
    return a.index - b.index
  })

  return pluck(res, 'value')
}

export default sortedBy
